/* Qust
 * 基于promise与ES6简易封装的XHR库
 * @Jan
 * @Version 2021-0413
 * 未做json适配,data统一格式为object
 */

import { Utils } from "/js/Utils.js";
class Qust extends Utils {
	constructor(arg) {
		super();
		let defaultInstanceConfig = {
			baseUrl: "",
			header: {},
			mode: "form-data",
		};
		this.config = super.merge(defaultInstanceConfig, arg);
	}

	create(arg) {
		return new Qust(arg);
	}

	request(arg) {
		let defaultRequestConfig = {
			method: "POST",
			data: null,
			url: "",
		};
		let sendConfig = super.merge(defaultRequestConfig, arg);

		if (this.config.mode == "form-data") {
			sendConfig.data = super.obj2FormData(sendConfig.data);
		}
		return new Promise((resolve, reject) => {
			let xhr = new XMLHttpRequest();

			// 填充数据
			xhr.open(sendConfig.method, this.config.baseUrl + sendConfig.url, true);

			// 设置header
			for (let key in this.config.header) {
				xhr.setRequestHeader(key, this.config.header[key]);
			}

			// 发送
			xhr.send(sendConfig.data);

			// 处理回调
			xhr.onreadystatechange = () => {
				if (xhr.readyState === 4) {
					if (xhr.status === 200) {
						resolve({
							code: xhr.status,
							data: JSON.parse(xhr.responseText),
						});
					} else {
						reject({
							code: xhr.status,
						});
					}
				}
			};
		});
	}
}

export default new Qust();
